package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.consts.CConsts;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CSessionTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountDetailView;
import com.fzrskj.cloud.free.user.utils.FuncHandleUtils;
import com.fzrskj.cloud.free.user.utils.UserAccountDetailUtils;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.XmlCodeParser;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserAccountDetailService extends CObject{

	/**财务明细(管理员)
	 * to query current login user account finance detail
	 * @param req
	 * @param resp
	 * @param p={"userName":"yyyy-MM-dd","start":"yyyy-MM-dd","end":"yyyy-MM-dd","subject":交易类型,"page":页数,"pagesize":每页条数}
	 * @param sid
	 * @return
	 */
	public String queryAdminAccount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CJsonTool.getStrValue(p, "userName", null);
		String sFrom = CJsonTool.getStrValue(p, "start", null);
		String sEnd  = CJsonTool.getStrValue(p, "end", null);
		//交易类型
		int subject	 = CJsonTool.getIntValue(p, "subject", 0);
		int page	 = CJsonTool.getIntValue(p, "page", 1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);

		Date dStart = CDateTimeTool.strToDate(sFrom);
		Date dEnd = CDateTimeTool.strToDate(sEnd);

		Map<String, Object> cdt = new HashMap<String, Object>();
		if (dStart!=null) {
			cdt.put("start", dStart);
		}
		if (dEnd!=null) {
			cdt.put("end", CDateTimeTool.incDay(dEnd,1));
		}
		if (subject>0) {
			cdt.put("itemId", subject);
		}
		if (!CStrTool.isBlankStr(userName)) {
			cdt.put("userName", userName);
		}

		UserAccountDetailUtils utls = new UserAccountDetailUtils();
		int rows = utls.queryAccountDetailNum(cdt);
		String err = utls.getErrCode();
		if (!err.equals(SysErr.CODE_SUCCESS)){
			utls.dispose();
			return XmlCodeParser.formatResultTips(false,err);
		}
		if (rows<(page-1)*pagesize){
			utls.dispose();
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_DATA_NOT_FOUND);
		}

		int pages = Math.round((rows+pagesize-1)/pagesize);
		List<UserAccountDetailView> list = utls.queryAccountDetailViewList(cdt, page, pagesize);
		err = utls.getErrCode();
		utls.dispose();
		if (!err.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, err);
		}

		double totalAmount=utls.queryAccountDetailAmount(cdt);
		String data = String.format("{\"list\":%s,\"totalAmount\":%s}",CJsonTool.listBeanToJson(list),totalAmount);
		return XmlCodeParser.formatResultPageData(err, page, pages, pagesize, rows, data);
	}

	/**
	 * 添加入款扣款数据记录
	 * @param req
	 * @param resp
	 * @param p{"itemId":"摘要Id","itemName":"记账摘要","userName":"用户名","amount":"金额","snId":"订单编号","bankCode":"付款方式","billno":"凭证号","remark":"备注描述"}
	 * @param sid
	 * @return
	 */
	public String addUserAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String adminName = CSessionTool.getAccountCloud(sid);
		int itemId = CJsonTool.getIntValue(p, "itemId", 0);
		String itemName=CJsonTool.getStrValue(p, "itemName", null);
		String userName = CJsonTool.getStrValue(p, "userName", null);
		double amount = CJsonTool.getFloatValue(p, "amount", 0);
		String snId = CJsonTool.getStrValue(p, "snId", null);
		String bankCode = CJsonTool.getStrValue(p, "bankCode", null);
		String billno = CJsonTool.getStrValue(p, "billno", null);
		String remark = CJsonTool.getStrValue(p, "remark", null);

		if (itemId <1 || CStrTool.isBlankStr(userName) || amount < 0 ||
				 CStrTool.isBlankStr(bankCode) ) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		BigDecimal bg = new BigDecimal(amount).setScale(2, RoundingMode.UP);
		amount=bg.doubleValue();

		//查询充值用户是否存在
		UserAccountUtils uaUtils = new UserAccountUtils();
		if(uaUtils.queryAccountByName(userName)==null){
			return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_EXISTS);
		}
		String detail="管理员【"+adminName+"】给会员【"+userName+"】"+itemName+"【¥"+amount+"】。备注："+remark;

		FuncHandleUtils utils = new FuncHandleUtils();
		String ret = utils.FinanceAccount(userName, itemId, detail, snId, bankCode, billno, amount,adminName);
		JSONObject json = JSONObject.fromObject(ret);
		if("-1".equals(json.getString("code"))){
			return XmlCodeParser.formatCustomTips(false, json.getString("message"));
		}
     	return XmlCodeParser.formatResultTips(true, SysErr.CODE_SUCCESS);
	}

	/**
	 * 获取记账记录
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String queryAccountConsume(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CSessionTool.getAccountCloud(sid);
		String sFrom = CJsonTool.getStrValue(p, "start", null);
		String sEnd  = CJsonTool.getStrValue(p, "end", null);
		float amount = CJsonTool.getFloatValue(p, "amount", 0); 	//发生额
		int subject	 = CJsonTool.getIntValue(p, "subject", 0);  	//交易类型
		String remark=CJsonTool.getStrValue(p, "remark", null);    	//备注
		String voucherId=CJsonTool.getStrValue(p, "voucherId", null);  //订单ID
		int page	 = CJsonTool.getIntValue(p, "page", 1);
		int pagesize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);

		Date dStart = CDateTimeTool.strToDate(sFrom);
		Date dEnd = CDateTimeTool.strToDate(sEnd);

		Map<String, Object> cdt = new HashMap<String, Object>();
		if (dStart!=null) {
			cdt.put("start", dStart);
		}
		if (dEnd!=null) {
			cdt.put("end", CDateTimeTool.incDay(dEnd,1));
		}
		if (amount>0) {
			cdt.put("amount", amount);
		}
		if (subject>0) {
			cdt.put("itemId", subject);
		}
		if (!CStrTool.isBlankStr(remark)) {
			cdt.put("remark", remark);
		}
		if (!CStrTool.isBlankStr(voucherId)) {
			cdt.put("voucherId", voucherId);
		}
		if (!CStrTool.isBlankStr(userName)) {
			cdt.put("userName", userName);
		}

		UserAccountDetailUtils utls = new UserAccountDetailUtils();
		int rows = utls.queryAccountDetailNum(cdt);
		String err = utls.getErrCode();
		if (!err.equals(SysErr.CODE_SUCCESS)){
			utls.dispose();
			return XmlCodeParser.formatResultTips(false,err);
		}
		if (rows<(page-1)*pagesize){
			utls.dispose();
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_DATA_NOT_FOUND);
		}

		int pages = Math.round((rows+pagesize-1)/pagesize);
		List<UserAccountDetailView> list = utls.queryAccountDetailViewList(cdt, page, pagesize);
		err = utls.getErrCode();
		utls.dispose();
		if (!err.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, err);
		}

		double totalAmount=utls.queryAccountDetailAmount(cdt);
		String data = String.format("{\"list\":%s,\"totalAmount\":%s}",CJsonTool.listBeanToJson(list),totalAmount);
		return XmlCodeParser.formatResultPageData(err, page, pages, pagesize, rows, data);
	}

	/**
	 * 消费统计
	 * @param req
	 * @param resp
	 * @param p={"itemId":"财务项","day":"查询天数"}  //day 1和默认查询为当天   2表示查询今天和昨天的  itemId 数据字典定义
	 * @param sid
	 * @return
	 */
	public String queryAccountDetailAmount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		//默认查询业务扣账
		int itemId = CJsonTool.getIntValue(p, "itemId", 300);
		int day = CJsonTool.getIntValue(p, "day", 0);

		Map<String, Object> map = new HashMap<String, Object>();
		if (itemId > 0) {map.put("itemId", itemId);}
		if (day >= 0) {
			map.put("start", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), -day)));
		}else{
			map.put("start", CDateTimeTool.dateToDateString(new Date()));
		}
		map.put("end", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), 1)));

		UserAccountDetailUtils userAccountUtils = new UserAccountDetailUtils();
		double ret = userAccountUtils.queryAccountDetailAmount(map);
		String code = userAccountUtils.getErrCode();
		userAccountUtils.dispose();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		if(ret>0){
			return XmlCodeParser.formatResultData(true, code,"\""+new java.text.DecimalFormat("#.00").format(ret)+"\"");
		}else{
			return XmlCodeParser.formatResultData(true, code,"\""+0+"\"");
		}
	}

	/**
	 * 会员查询消费统计
	 * @param req
	 * @param resp
	 * @param p={"itemid":"记账类型","startTime":"开始时间","endTime":"结束时间"}
	 * @param sid
	 * @return
	 */
	public String UserAccountDetailCount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();
		String startTime = CJsonTool.getStrValue(p, "startTime", "");
		String endTime = CJsonTool.getStrValue(p, "endTime", "");
		String itemId = CJsonTool.getStrValue(p, "itemId", "");

		Date dStart = CDateTimeTool.strToDate(startTime);
		Date dEnd = CDateTimeTool.strToDate(endTime);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", uid);
		if (!CStrTool.isBlankStr(startTime)) {map.put("start", dStart);}
		if (!CStrTool.isBlankStr(endTime)) {map.put("end", CDateTimeTool.incDay(dEnd,1));}
		if (!CStrTool.isBlankStr(itemId)) {map.put("itemId", itemId);}

		UserAccountDetailUtils userAccountUtils = new UserAccountDetailUtils();
		double total = userAccountUtils.queryAccountDetailAmount(map);
		String code = userAccountUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"total\":%s}",total);
		return XmlCodeParser.formatResultData(true, code,data);
	}

	/**
	 * 管理员查询消费统计
	 * @param req
	 * @param resp
	 * @param p={"userid":"用户ID","itemid":"记账类型","startTime":"开始时间","endTime":"结束时间"}
	 * @param sid
	 * @return
	 */
	public String AdminAccountDetailCount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String startTime = CJsonTool.getStrValue(p, "startTime", "");
		String endTime = CJsonTool.getStrValue(p, "endTime", "");
		String itemId = CJsonTool.getStrValue(p, "itemId", "");
		String userName = CJsonTool.getStrValue(p, "userName", "");

		Date dStart = CDateTimeTool.strToDate(startTime);
		Date dEnd = CDateTimeTool.strToDate(endTime);

		Map<String, Object> map = new HashMap<String, Object>();
		if (!CStrTool.isBlankStr(startTime)) {map.put("start", dStart);}
		if (!CStrTool.isBlankStr(endTime)) {map.put("end", CDateTimeTool.incDay(dEnd,1));}
		if (!CStrTool.isBlankStr(itemId)) {map.put("itemId", itemId);}
		if (!CStrTool.isBlankStr(userName)) {map.put("userName", userName);}

		UserAccountDetailUtils uadUtils = new UserAccountDetailUtils();
		double total = uadUtils.queryAccountDetailAmount(map);
		String code = uadUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"total\":%s}",total);
		return XmlCodeParser.formatResultData(true, code,data);
	}

	/**
	 * 根据用户名获得可开票金额
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	 public String getAllSureInvoice(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String userName = CSessionTool.getAccountCloud(sid);
		UserAccountDetailUtils uadUtils = new UserAccountDetailUtils();
		double total = uadUtils.getAllSureInvoice(userName);
		String code = uadUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"total\":%s}",total);
		return XmlCodeParser.formatResultData(true, code,data);
	}

	 /**
	 * 获取财务记账详情(会员)
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String queryUserAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();

		int id=CJsonTool.getIntValue(p, "id", 0);
		Map<String, Object> cdt = new HashMap<String, Object>();
		cdt.put("id", id);
		cdt.put("userId", uid);

		UserAccountDetailUtils uadUtils = new UserAccountDetailUtils();
		UserAccountDetailView view=uadUtils.queryUadView(cdt);
		String code = uadUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"view\":%s}",CJsonTool.beanToJson(view));
		return XmlCodeParser.formatResultData(true, code,data);
	}

	/**
	 * 获取财务记账详情(管理员)
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String queryAdminAccountDetail(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int id=CJsonTool.getIntValue(p, "id", 0);
		Map<String, Object> cdt = new HashMap<String, Object>();
		cdt.put("id", id);

		UserAccountDetailUtils uadUtils = new UserAccountDetailUtils();
		UserAccountDetailView view=uadUtils.queryUadView(cdt);
		String code = uadUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String data = String.format("{\"view\":%s}",CJsonTool.beanToJson(view));
		return XmlCodeParser.formatResultData(true, code,data);
	}

	/**
	 * 收入统计(管理员)
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */ 
	public String queryAccountIncome(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int day = CJsonTool.getIntValue(p, "day", 0);

		Map<String, Object> map = new HashMap<String, Object>();
		if (day>=0) {
			map.put("start", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), -day)));
		}
		map.put("end", CDateTimeTool.dateToDateString(CDateTimeTool.incDay(new Date(), 1)));
		
		UserAccountDetailUtils userAccountUtils = new UserAccountDetailUtils();
		double total = userAccountUtils.queryAccountIncome(map);
		String code = userAccountUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		
		String data = String.format("{\"total\":%s}",total);
		return XmlCodeParser.formatResultData(true,code,data);
	}
}